package com.example.api.project.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.tomcat.util.codec.binary.Base64;

 
public class ApiSecurityExample {

  
  
  public static String change( String secret,String message) {
String back=null;
	    try {
	 
	     Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
	     SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
	     sha256_HMAC.init(secret_key);
	 
	     String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));

	     byte[] bytes = sha256_HMAC.doFinal(message.getBytes());   
	      hash = byteArrayToHexString(bytes); 
	     return hash;
	    }
	    catch (Exception e){
	     System.out.println("Error");
	    }
		return back;
	   
	
}
  private static String byteArrayToHexString(byte[] b) {  
      StringBuilder hs = new StringBuilder();     
      String stmp;      
  for (int n = 0; b!=null && n < b.length; n++) {   
         stmp = Integer.toHexString(b[n] & 0XFF);    
         if (stmp.length() == 1)           
         hs.append('0');      
         hs.append(stmp);    
    }      
   return hs.toString().toLowerCase();   
 } 
  /**
  * 利用java原生的类实现SHA256加密
  * @param str 加密后的报文
  * @return
  */
  public static  String getSHA256(String str){
    MessageDigest messageDigest;
   String encodestr = "";
   try {
    messageDigest = MessageDigest.getInstance("SHA-256");
    messageDigest.update(str.getBytes("UTF-8"));
    encodestr = byte2Hex(messageDigest.digest());
   } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
   } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
   }
   return encodestr;
  }
  /**
  * 将byte转为16进制
  * @param bytes
  * @return
  */
  private static String byte2Hex(byte[] bytes){
   StringBuffer stringBuffer = new StringBuffer();
   String temp = null;
   for (int i=0;i<bytes.length;i++){
    temp = Integer.toHexString(bytes[i] & 0xFF);
    if (temp.length()==1){
    //1得到一位的进行补0操作
    stringBuffer.append("0");
    }
    stringBuffer.append(temp);
   }
   return stringBuffer.toString();
  }



}